/*
 * @Author: ZWS
 * @Date: 2022-02-14 17:25:04
 * @LastEditTime: 2022-02-15 17:26:12
 * @Description: axios 请求封装
 */
import { Axios } from 'axios'

// {
//   baseURL: 'https://some-domain.com/api/',
//     timeout: 1000,
//       headers: { 'X-Custom-Header': 'foobar' }
// }
class BaseRequest {
  public axios: Axios;
  constructor (config: any) {
    this.axios = new Axios(config)

    // 请求拦截器
    this.axios.interceptors.request.use((config) => {
      return config
    }, (error) => {
      return Promise.reject(error)
    })

    // 响应拦截器
    this.axios.interceptors.response.use((response) => {
      // 2xx 范围内的状态码都会触发该函数。
      if (response.status === 200) {
        return response
      }
    }, (error) => {
      // 超出 2xx 范围的状态码都会触发该函数。
      return Promise.reject(error)
    })
  }

  public get (url: string, data: ObjectStringKey): Promise<Response> {
    let params: string = ''
    Object.keys(data).forEach(key => {
      params += `${key}=${typeof data[key] === 'object' ? JSON.parse(data[key]) : data[key]}&`
    })
    params = params.substring(0, params.length - 1)
    return this.axios.get(`${url}?${params}`, this.getConfig())
  }

  public post (url: string, data: any): Promise<Response> {
    return this.axios.post(url, data, this.getConfig())
  }

  public delete (url: string, data: ObjectStringKey): Promise<Response> {
    let params: string = ''
    Object.keys(data).forEach(key => {
      params += `${key}=${typeof data[key] === 'object' ? JSON.parse(data[key]) : data[key]}&`
    })
    return this.axios.delete(`${url}?${params}`, this.getConfig())
  }

  public put (url: string, data: any): Promise<Response> {
    return this.axios.put(url, data, this.getConfig())
  }

  public patch (url: string, data: any): Promise<Response> {
    return this.axios.patch(url, data, this.getConfig())
  }

  private getConfig (config?: any): any {
    return {

    }
  }
}

export default BaseRequest
